<?php

namespace core;

use core\lib\Exception;
use core\lib\Response;
use core\lib\Route;

/**
 * 主入口和出口
 */
class Server
{
    static public $classMap = array();

    static public function run()
    {
        try {
            //路由规则
            $route = new Route();
            $ctrlClass = ucfirst($route->ctrl);
            $action = $route->action;
            $ctrlfile = APP . '/ctrl/' . $ctrlClass . '.php';
            if (!is_file($ctrlfile)) {
                error('查找不到控制器', 404);
            }
            $cltrlClass = '\\app\ctrl\\' . $ctrlClass;
            $ctrl = new $cltrlClass();

            //调用控制器
            if (method_exists($ctrl, '__initialize')) {
                $ctrl->__initialize();
            }
            if (!method_exists($ctrl, $action)) {
                error('查找不到方法', 404);
            }
            $data = [
                'code' => 200,
                'result' => $ctrl->$action(),
            ];
        } catch (\Exception $e) {
            $Exception = new Exception();
            $data = $Exception->render($e);
        }
        $Response = new Response();
        $Response->create($data);
    }

    /**
     * 自动加载指定类
     */
    static public function load($class)
    {
        if (isset($classMap[$class])) {
            return true;
        } else {
            $class = str_replace('\\', '/', $class);
            $file = BASE_PATH . '/' . $class . '.php';
            if (is_file($file)) {
                include $file;
                self::$classMap[$class] = $class;
            } else {
                return false;
            }
        }
    }

    public function assign($name, $value)
    {
        $this->assign[$name] = $value;
    }

    public function display($file)
    {
        $file = APP . '/view/' . $file;
        if (is_file($file)) {
            extract($this->assign);
            include $file;
        }
    }
}
